﻿using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using UserRegistration.Model.DP;
using UserRegistration.Model.OOP;

namespace UserRegistration.Repository.Impl
{
    public class RegistrationServiceImpl : IRegistrationService
    {
        private SalesRepRepository _salesRepRepo;
        private UserRepository _userRepo;

        public RegistrationServiceImpl(SalesRepRepository salesRepRepo, UserRepository userRepo)
        {
            _salesRepRepo = salesRepRepo;
            _userRepo = userRepo;
        }

        public User Register(string name, string phone, string address)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ValidationException("name");
            }
            if (string.IsNullOrWhiteSpace(phone) || !IsValidPhoneNumber(phone))
            {
                throw new ValidationException("phone");
            }
            // 此处省略address的校验逻辑 取电话号里的区号，

            UserName _name = new UserName(name);
            PhoneNumber _phone = new PhoneNumber(phone);
            Address _address = new Address(address);
          
            var rep = _salesRepRepo.FindRep(_phone.GetAreaCode());
            // 最后创建用户，落盘，然后返回
            User user = new User
            {
                Name = name,
                Phone = phone,
                Address = address
            };
            if (rep != null)
            {
                user.RepId = rep.RepId;
            }

            return _userRepo.Save(user);
        }

        /// <summary>
        /// 验证电话号码
        /// </summary>
        private bool IsValidPhoneNumber(string phone)
        {
            string pattern = "^0[1-9]{2,3}-?\\d{8}$";
            return Regex.IsMatch(phone, pattern);
        }

        public User Register(UserName name, PhoneNumber phone, Address address)
        {
            // 找到区域内的 SalesRep
            var rep = _salesRepRepo.FindRep(phone.GetAreaCode());
            // 最后创建用户，落盘，然后返回，这部分代码实际上也能用 Builder 解决
            var user = new Model.Entity.User
            {
                Name = name,
                Phone = phone,
                Address = address
            };
            if (rep != null)
            {
                user.RepId = rep.RepId;
            }
            return _userRepo.Save(user);
        }
    }
}